<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Models\ActivityClassif;
use App\Models\Activity;
use App\Models\ActivityJoin;
use App\Models\Banner;
use App\Models\UsersWechat;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Cache;
use Tymon\JWTAuth\Facades\JWTAuth;
use Validator;
use Illuminate\Support\Facades\DB;

class ActivityController extends Controller
{


    public function postPageRows(Request $request){
        //讲定时发布的活动符合时间设置转成发布状态
        Activity::where('status',10)->where('publish_time','<',date('Y-m-d H:i:s'))->update(['status'=>1]);
        $date = $request->input('date');
        $class_id = $request->input('class');
        $query = Activity::with('class')->where('status','<>',0);
        $time = date('Y/m/d H:i:s',time());
        if ($date) {
            $startTime = date('Y-m-01', strtotime($date.'/01'));
            $endTime = date('Y-m-d 23:59:59', strtotime("$startTime +1 month -1 day"));
            $query->whereBetween('start_time',[$startTime, $endTime]);
        }
        if ($class_id) {
            $query->where('class_id',$class_id);
        }
        $rows =$query->paginate(15);
        foreach ($rows as $key => $row) {
            $picArr = unserialize($row->pic1);
            foreach ($picArr as $k => $pic) {
                $picArr[$k] = url($pic);
            }
            $row->pic1 = $picArr;
            if ($user = $this->JwtChecking($request)) {
                $join = ActivityJoin::where(['wechat_id'=>$user->id,'activity_id'=>$row->id])->count('id');
                $row->is_join = $join ? 1 :0;
                $row->joinName = $join ? '已报名' : '未报名';
            }
        }
        $user = JWTAuth::parseToken()->authenticate();
        $wechat_id = $user->id;
        $joinCount = ActivityJoin::with('activity')->where('wechat_id',$wechat_id)->count('id');
        $data = [
            'rows' => $rows,
            'joinCount' =>$joinCount,
        ];
        return response()->json(['code' => 1,'msg' =>'Success','data' => $data]);
    }

    public function postActivityInfo(Request $request,$id){
        $row = Activity::with('class')->where('status','<>',0)->find($id);//不是草稿
        if (!$row) {
            return response()->json(['code' => -1,'msg' =>'活动不存在！','data' =>'']);
        }
        if ($user = $this->JwtChecking($request)) {
            //报名信息
            $row->join =  ActivityJoin::where(['wechat_id'=>$user->id,'activity_id'=>$id])->first();
        }
        $picArr = unserialize($row->pic1);
        foreach ($picArr as $k => $pic) {
            $picArr[$k] = url($pic);
        }
        $row->pic1 = $picArr;
        $user = JWTAuth::parseToken()->authenticate();
        $wechat_id = $user->id;
        $join = ActivityJoin::where(['wechat_id'=>$wechat_id,'activity_id'=>$row->id])->count('id');
        $joinSurplus = DB::table('activity_join_number')->where('wechat_id',$wechat_id)->count('id');
        // $joinSurplus = config('services.joinSurplus') - ActivityJoin::where(['wechat_id'=>$wechat_id])->count('id');
        $row->is_join = $join ? 1 :0;
        $row->joinName = $join ? '已报名' : '未报名';
        $row->joinSurplus = $joinSurplus < 0 ? 0 : $joinSurplus;//剩余报名次数
        $row->notes = explode("\r\n", $row->notes);;

        $joinCount = ActivityJoin::with('activity')->where('wechat_id',$wechat_id)->count('id');
        $data = [
            'row' => $row,
            'joinCount' =>$joinCount,
        ];
         return response()->json(['code' => 1,'msg' =>'Success','data' =>$data]);
    }

    //参加活动
    public function postJoin(Request $request,$activity_id){
        if (!$activity_id) {
            return response()->json(['code' => -1,'msg' =>'参数错误','data' =>null]);
        }

        if ($user = $this->JwtChecking($request)) {
            $wechat_id = $user->id;
            //非会员
            if (!$user->type) {

                $validator = Validator::make($request->all(),
                [
                    'username' => 'required',
                    'mobile' => ['required','regex:/^1[3|4|5|6|7|8|9][0-9]\d{4,8}$/'],
                    'age' => 'required|integer',
                    'sex' => 'required',
                    'occupation' => 'required',
                    'position' => 'required',
                ],[
                    'required' => ':attribute 不能为空.',
                    'integer'=>':attribute 必须是数值',
                    'regex'=>':attribute 格式不正确',
                ]);
                if ($validator->fails()) {
                    $messages = $validator->errors();
                    return response()->json(['code' => -1,'msg' => $messages->first(),'data' => '',]);
                }

                $join = ActivityJoin::where('wechat_id',$wechat_id)->where('activity_id',$activity_id)->first();
                if (!$join) {
                    return response()->json(['code' => -1,'msg' =>'对不起；您还不是思凯乐box会员;请先进行支付','data' =>null]);
                }
                $join->username= safe2($request->input('username'));
                $join->mobile= safe2($request->input('mobile'));
                $join->age= safe2($request->input('age'));
                $join->sex= safe2($request->input('sex'));
                $join->occupation= safe2($request->input('occupation'));
                $join->position= safe2($request->input('position'));
                $join->save();
            }else{
                //会员
                $joinSurplus = DB::table('activity_join_number')->where('wechat_id',$wechat_id)->count('id');
                // $joinSurplus = config('services.joinSurplus') - ActivityJoin::where(['wechat_id'=>$wechat_id])->count('id');
                if ($joinSurplus  <= 0 ) {
                    $join = ActivityJoin::where('wechat_id',$wechat_id)->where('activity_id',$activity_id)->first();
                    if (!$join) {
                        return response()->json(['code' => -1,'msg' =>'会员免费资格已用完；请先进行支付费用','data' =>null]);
                    }
                }else{
                    $join = ActivityJoin::where(['wechat_id'=>$wechat_id,'activity_id'=>$activity_id])->first();
                    if (!$join) {
                        $join = new ActivityJoin();
                        $join->wechat_id = $wechat_id;
                        $join->activity_id= $activity_id;
                        $join->is_vip= $user->number;
                        $join->save();
                    }else{
                        $join->is_vip= $user->number;
                        $join->save();
                    }
                }
            }

            return response()->json(['code' => 1,'msg' =>'Success','data' =>$join]);
        }else{
             return response()->json(['code' => -401,'msg' => 'token_not_provided：token不存在','data' => '',]);
        }

    }

    //分类
    public function getActivityClassifPageRows(Request $request)
    {
        $rows = ActivityClassif::get();
        return response()->json(['code' => 1,'msg' => 'Success','data' =>['rows'=>$rows]]);
    }

    //banner
    public function getBanner(Request $request)
    {
        $rows = Activity::select('id','title','pic1')->where('is_pro',1)->get();
        foreach ($rows as $key => $row) {
            $picArr = unserialize($row->pic1);
            $row->pic1 = url(reset($picArr));
        }
        $data = [
            'rows' => $rows,
        ];
        return response()->json(['code' => 1,'msg' => 'Success','data' =>$data]);
    }

}
